<html>
<head>
	<script>

		var username;
		var requestDelay;
		var notification;

		var requestTimeout = 1000 * 15;
		
		var memeValues = { "notification": [
			{ "prop": "memes", "value": 0 },
			{ "prop": "replies", "value": 0 },
			{ "prop": "memes_private", "value": 0 },
			{ "prop": "replies_private", "value": 0 },
			{ "prop": "mentions", "value": 0 },
			{ "prop": "followers", "value": 0 }
		]};

		function init() { 

			if( !localStorage.username || localStorage.username == "" ) {
				errorHandler( "Opt" );
				return;
			}
	
			username = localStorage.username;
			requestDelay = localStorage.requestDelay;

			if( isNaN( requestDelay ) || requestDelay < 30 ) {
				errorHandler( "Opt" );
				return;
			}

			notification = localStorage.notification;
			unreadCounter();
		}

		function errorHandler( badgeText ) {
			if( badgeText == "LIn" )
				openMeemi( null );
			chrome.browserAction.setBadgeText({ text: badgeText });
		}

		function unreadCounter() {
			var request = new XMLHttpRequest();
	
			var abortTimerId = window.setTimeout(function() {
				console.log( "Mancata conferma della comunicazione entro: " + requestTimeout );
				errorHandler( "TOut" );
				request.abort();
			}, requestTimeout);
			
			request.open( "GET", getMeemiApiUrl( "notify" ), true );
			request.onreadystatechange = function() {

				var badgeText = "";
				if( request.readyState == 4 && request.status == 200 ) {
					window.clearTimeout( abortTimerId );
					if( request.responseXML ) {
						console.log( "Ricevuto documento XML." );
			
						var notifyElement = request.responseXML.getElementsByTagName( "notify" )[0];
						if( !notifyElement ) {
							console.log( "Documento XML non riconosciuto." );
							errorHandler( "LIn" );
							return;
						}
						
						var badgeValue = 0;
			
						for( var index = 0, value; index < notifyElement.attributes.length; index++ ) {
							value = parseInt( notifyElement.attributes[index].nodeValue );
							memeValues.notification[index].value = value;
							if( getFlag( index ) > 0 )
								badgeValue += value;
						}

						if( badgeValue > 0 )
							badgeText = badgeValue.toString();
			
						chrome.browserAction.setBadgeText( {text: badgeText} );
					}
					window.setTimeout( unreadCounter, requestDelay );
				}
			}

			request.send( null );
		}

		function getFlag( flagPosition ) {
			if( flagPosition < 0 && flagPosition > 5 )
				return 0;
			var meemiNotification = 5 - flagPosition;
			var mask = 1 << meemiNotification;
			if(( notification & mask ) == 0 )
				return 0;
			return 1;
		}

		function getMeemiApiUrl( addings ) {
			var url = "http://meemi.com/api/" +
				username + "/" +
				addings;
			return url;
		}

		function isMeemiUrl( url ) {
			return url.indexOf( "http://meemi.com/" ) == 0;
		}

		function getMeemiUrl( addings ) {
			return "http://meemi.com/" +
				localStorage.username + "/" +
				addings;
		}

		chrome.tabs.onUpdated.addListener( function( tabId, changeInfo ) {
			if( changeInfo.url ) {
				if ( isMeemiUrl( changeInfo.url ))
					unreadCounter(); }
			else
				chrome.tabs.getSelected( undefined, function( tab ) {
					if( isMeemiUrl( tab.url ))
						unreadCounter();
				});
		});

		function openMeemi( selectedTab ) {
			chrome.tabs.getAllInWindow( undefined, function( tabs ) {
				for( var i = 0, tab; tab = tabs[i]; i++ ) {
					if ( tab.url && isMeemiUrl( tab.url )) {
						chrome.tabs.update(tab.id, {selected: true});
						return;
					}
				}
				chrome.tabs.create({ url: getMeemiUrl( "wf" )});
			});
		}

		chrome.browserAction.onClicked.addListener( openMeemi );
		
		chrome.extension.onRequest.addListener( function( request, sender, sendResponse ) {
			if( request.validation == "notification" ) {
				console.log( "Send Response." );
				sendResponse( memeValues ); }
			else
				sendResponse({}); // Empty obj, to close the request.
		});

	</script>
</head>
<body onload="init()">
</body>
</html>
